<template>
  <base-layout @tenant-change="changeTenant">
    <article class="base-layout__inner column">
      <tiny-form :schema="formSchema" layout="inline" :model="queryParams"></tiny-form>
      <t-table
        row-key="id"
        :columns="tableSchema"
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        @page-change="onPageChange"
        bordered
        size="small"
      ></t-table>
    </article>
  </base-layout>
</template>

<script>
import TinyForm from '@/components/tiny/TinyForm.vue';
import TinyTable from '@/components/tiny/TinyTable.vue';
import { AddIcon } from 'tdesign-icons-vue';
import BaseLayout from '@/components/base-layout/index.vue';
import { Button as TButton } from 'tdesign-vue';
import { getUserListNormal } from '@/api/user';
import {mapGetters} from "vuex";

export default {
  name: 'OperationUser',
  components: {
    TinyForm,
    TinyTable,
    AddIcon,
    BaseLayout,
  },
  data() {
    return {
      loading: false,
      formSchema: [
        {
          label: '组织',
          prop: 'tenantName',
          component: 'Input',
          labelWidth: '80px'
        },
        {
          label: '昵称',
          prop: 'nickname',
          component: 'Input',
          labelWidth: '80px'
        },
        {
          label: '手机号',
          prop: 'phone',
          component: 'Input',
          labelWidth: '80px'
        },
        {
          slots: (h) => {
            return h('span', {}, [
              h(
                TButton,
                {
                  props: {
                    theme: 'primary',
                    variant: 'base',
                  },
                  on: {
                    click: () => {
                      this.handleSearch();
                    },
                  },
                },
                '查询'
              ),
              h(
                TButton,
                {
                  style: {
                    marginLeft: '8px',
                  },
                  props: {
                    theme: 'default',
                    variant: 'base',
                  },
                  on: {
                    click: () => {
                      this.handleReset();
                    },
                  },
                },
                '重置'
              ),
            ]);
          },
        },
      ],
      tableSchema: [
        {
          colKey: 'index',
          title: '序号',
          width: 80,
          cell: (h, { rowIndex }) => {
            const index = (this.pagination.current - 1) * this.pagination.pageSize + rowIndex + 1;
            return h('span', index);
          },
        },
        {
          colKey: 'id',
          title: 'ID',
          width: 80,
        },
        {
          colKey: 'tenantName',
          title: '组织名称',
          width: 120,
          cell: (h, { row }) => {
            return h('t-tag', {
              props: {
                theme: 'primary',
                variant: 'light'
              }
            }, row?.tenant?.name ?? '-');
          },
        },
        {
          colKey: 'nickname',
          title: '昵称',
          width: 160,
          cell: (h, { row }) => {
            return row?.wechat?.nickname ?? '-';
          },
        },
        {
          colKey: 'phone',
          title: '手机号',
          width: 130,
          cell: (h, { row }) => {
            return row?.wechat?.phone
              ? row.wechat.phone.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
              : '-';
          },
        },
        {
          colKey: 'healthPoints',
          title: '健康积分',
          width: 100,
          align: 'center',
          cell: (h, { row }) => {
            const score = row?.wechat?.healthPoints || 0;
            return h('span', { style: { color: '#222' } }, score);
          },
        },
        {
          colKey: 'bmi',
          title: 'BMI',
          width: 100,
          align: 'center',
          cell: (h, { row }) => {
            const bmi = parseFloat(row?.wechat?.bmi) || 0;
            return h('span', { style: { color: '#222' } }, bmi.toFixed(1));
          },
        },
        {
          colKey: 'bloodPressure',
          title: '血压(mmHg)',
          width: 120,
          align: 'center',
          cell: (h, { row }) => {
            const systolic = row?.wechat?.bloodPressureSbp || 0;
            const diastolic = row?.wechat?.bloodPressureDbp || 0;
            const pressure = `${systolic}/${diastolic}`;
            return h('span', { style: { color: '#222' } }, pressure);
          },
        },
        {
          colKey: 'bloodSugar',
          title: '空腹血糖(mmol/L)',
          width: 150,
          align: 'center',
          cell: (h, { row }) => {
            const sugar = parseFloat(row?.wechat?.fastingBloodGlucose) || 0;
            return h('span', { style: { color: '#222' } }, sugar.toFixed(1));
          },
        },
        {
          colKey: 'createdAt',
          title: '注册时间',
          width: 180,
          cell: (h, { row }) => {
            return row?.createdAt ? new Date(row.createdAt).toLocaleString() : '-';
          },
        },
        {
          title: '操作',
          width: 120,
          fixed: 'right',
          cell: (h, { row }) => {
            return h('span', {}, [
              h(
                TButton,
                {
                  props: {
                    variant: 'text',
                    theme: 'primary',
                    size: 'medium'
                  },
                  on: {
                    click: () => {
                      this.handleSwitchTenant(row);
                    },
                  },
                },
                '切换组织'
              ),
            ]);
          },
        },
      ],
      tableData: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showJumper: true,
        showPageSize: true,
        pageSizeOptions: [10, 20, 50, 100],
      },
      queryParams: {
        tenantName: '',
        nickname: '',
        phone: '',
      },
    };
  },
	computed: {
		...mapGetters({
      tenantId: 'user/tenantId',
      isSuperAdmin: 'user/isSuperAdmin',
    }),
	},
	mounted() {
		this.getUserListNormal();
	},
  methods: {
    async getUserListNormal() {
      this.loading = true;
      try {
        const params = {
          page: this.pagination.current,
          pageSize: this.pagination.pageSize,
          nickname: this.queryParams.nickname,
          phone: this.queryParams.phone,
          tenantName: this.queryParams.tenantName,
        };

        // 清理空值参数
        Object.keys(params).forEach((key) => {
          if (params[key] === '' || params[key] === null) {
            delete params[key];
          }
        });

        const response = await getUserListNormal(params);

        // 处理返回数据
        if (response && response.data && response.data.data) {
          this.tableData = Array.isArray(response.data.data.data) ? response.data.data.data : [];
          this.pagination.total = Number(response.data.data.total) || 0;
          this.pagination.current = Number(response.data.data.page) || this.pagination.current;
          this.pagination.pageSize = Number(response.data.data.pageSize) || this.pagination.pageSize;
        } else {
          this.tableData = [];
          this.pagination.total = 0;
        }
      } catch (error) {
        console.error('获取用户列表失败:', error);
        this.$message.error('获取用户列表失败');
        this.tableData = [];
        this.pagination.total = 0;
      } finally {
        this.loading = false;
      }
    },

    // 查询
    handleSearch() {
      this.pagination.current = 1;
      this.getUserListNormal();
    },

    // 重置
    handleReset() {
      this.queryParams = {
        tenantName: '',
        nickname: '',
        phone: '',
      };
      this.pagination.current = 1;
      this.getUserListNormal();
    },

    // 分页变化
    onPageChange({ current, pageSize }) {
      this.pagination.current = current;

      if (pageSize !== this.pagination.pageSize) {
        this.pagination.current = 1;
      }

      this.pagination.pageSize = pageSize;

      this.getUserListNormal();
    },

    changeTenant(tenant) {
      this.getUserListNormal();
    },

    handleSwitchTenant(row) {
      this.$message.info(`切换到组织: ${row?.tenant?.name || '未知组织'}`);
      // 这里可以添加切换租户的具体逻辑
    },
  },
};
</script>

<style lang="less" scoped></style>
